
package com.yzkj.cpjxc.business.framework.common.uploadify;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public final class FileTypeUtils {

	/** * 将文件头转换成16进制字符串 * * @param 原生byte * @return 16进制字符串 */
	/**
	 * @description: 将文件头转换成16进制字符串
	 */
	private static String bytesToHexString(byte[] src) {
		StringBuilder stringBuilder = new StringBuilder();
		if (src == null || src.length <= 0) {
			return null;
		}
		for (int i = 0; i < src.length; i++) {
			int v = src[i] & 0xFF;
			String hv = Integer.toHexString(v);
			if (hv.length() < 2) {
				stringBuilder.append(0);
			}
			stringBuilder.append(hv);
		}
		return stringBuilder.toString();
	}

	/**
	 * @description: 得到文件头
	 */
	private static String getFileContent(String filePath) throws IOException {
		byte[] b = new byte[28];
		InputStream inputStream = null;
		try {
			inputStream = new FileInputStream(filePath);
			inputStream.read(b, 0, 28);
		} catch (IOException e) {
			e.printStackTrace();
			throw e;
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
					throw e;
				}
			}
		}
		return bytesToHexString(b);
	}

	/**
	 * @description: 根据文件路径获取类型
	 */
	public static FileType getType(String filePath) throws IOException {
		String fileHead = getFileContent(filePath);
		if (fileHead == null || fileHead.length() == 0) {
			return null;
		}
		fileHead = fileHead.toUpperCase();
		FileType[] fileTypes = FileType.values();
		for (FileType type : fileTypes) {
			if (fileHead.startsWith(type.getValue())) {
				return type;
			}
		}
		return null;
	}

	/**
	 * @description: 得到文件头
	 */
	private static String getFileContent(byte[] fileByte) throws IOException {
		if (fileByte.length < 28) {
			return null;
		}
		byte[] b = new byte[28];
		for (int i = 0; i < 28; i++) {
			b[i] = fileByte[i];
		}
		return bytesToHexString(b);
	}

	/**
	 * @description: 根据文件字节获取类型
	 */
	public static FileType getType(byte[] fileByte) throws IOException {
		String fileHead = getFileContent(fileByte);
		if (fileHead == null || fileHead.length() == 0) {
			return null;
		}
		fileHead = fileHead.toUpperCase();
		FileType[] fileTypes = FileType.values();
		for (FileType type : fileTypes) {
			if (fileHead.startsWith(type.getValue())) {
				return type;
			}
		}
		return null;
	}

	/**
	 * @description: 查看目标文件类型是否包含在类型数组里面
	 */
	public static boolean isContain(FileType typeTarget, FileType... types) {
		for (FileType t : types) {
			if (t.equals(typeTarget)) {
				return true;
			}
		}
		return false;
	}
}
